#!/usr/bin/python
from __future__ import with_statement
import os,sys,re

before='''if(test -L $0) then auxlink=`ls -l $0 | sed 's/^[^>]*-> //g'`; M_HOME=`dirname $auxlink`/; else M_HOME=`dirname $0`/; fi; cd $M_HOME
. ../before || exit 1\n'''
after='touch $ROOTFS/.`basename $0`\n'

os.chdir('..')
if os.path.exists('scripts')==False: raise Exception('"scripts/" not found.')

for script in os.listdir('scripts'):
	path = os.path.join('scripts', script)
	if os.path.isdir(path): continue
	with open(path) as f:
		v1 = f.read()
		f.seek(0)
		contents = f.readlines()
	if (before in v1) and (after in contents): continue
	if not before in v1: contents.insert(1, before)
	if not after in contents: contents.append(after)
	v2 = ''.join(contents)
	v2 = v2.replace('/opt/armgcc/rootfs', '$ROOTFS')
	v2 = v2.replace('/opt/9263/rootfs', '$ROOTFS')
	print '\n Wrap %s \n'%script
	print 'Before:\n\n%s\n'%v1
	print 'After:\n\n%s\n'%v2
	if raw_input('Apply? (y/n)')=='y':
		with open(path, 'w') as f:
			f.write(v2)
